/*
 * @Author: davon 2230383936@qq.com
 * @Date: 2025-06-14 16:20:40
 * @LastEditors: davon 2230383936@qq.com
 * @LastEditTime: 2025-07-24 22:46:42
 * @FilePath: \test-aliyunc:\Users\Davon\Desktop\LPP\HTML\script.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE,
 */
const { createApp, ref, computed, watch } = Vue
const { ElMessage, ElMessageBox } = ElementPlus
// 产品配置
const products = {
    // 产品识别规则
    patterns: {
        // 快递公司匹配规则
        express: {
            sf: /顺丰/,
            default: '韵达'
        },
        // 省份匹配规则
        provinces: {
            '北京': /北京|北京市/,
            '天津': /天津|天津市/,
            '河北': /河北|河北省/,
            '山西': /山西|山西省/,
            '内蒙古': /内蒙古|内蒙古自治区/,
            '辽宁': /辽宁|辽宁省/,
            '吉林': /吉林|吉林省/,
            '黑龙江': /黑龙江|黑龙江省/,
            '上海': /上海|上海市/,
            '江苏': /江苏|江苏省/,
            '浙江': /浙江|浙江省/,
            '安徽': /安徽|安徽省/,
            '福建': /福建|福建省/,
            '江西': /江西|江西省/,
            '山东': /山东|山东省/,
            '河南': /河南|河南省/,
            '湖北': /湖北|湖北省/,
            '湖南': /湖南|湖南省/,
            '广东': /广东|广东省/,
            '广西': /广西|广西壮族自治区/,
            '海南': /海南|海南省/,
            '重庆': /重庆|重庆市/,
            '四川': /四川|四川省/,
            '贵州': /贵州|贵州省/,
            '云南': /云南|云南省/,
            '西藏': /西藏|西藏自治区/,
            '陕西': /陕西|陕西省/,
            '甘肃': /甘肃|甘肃省/,
            '青海': /青海|青海省/,
            '宁夏': /宁夏|宁夏回族自治区/,
            '新疆': /新疆|新疆维吾尔自治区/,
            '台湾': /台湾|台湾省/,
            '香港': /香港|香港特别行政区/,
            '澳门': /澳门|澳门特别行政区/
        }
    },
    
    // 快递费用配置
    expressFees: {
        '韵达': {
            shippingFee: 4,    // 运费
            shippingCost: 2    // 运费成本
        },
        '顺丰': {
            shippingFee: 8,    // 运费
            shippingCost: 3.5  // 运费成本
        }
    },
    
    // 产品信息配置
    items: {
        'X2': {
            name: 'X2',
            price: 33,
            cost: 32,
        },
        'X3': {
            name: 'X3',
            price: 32,  // 售价
            cost: 31,   // 成本
        },
        'X4': {
            name: 'X4',
            price: 34,
            cost: 32,
        },
        'X5': {
            name: 'X5',
            price: 32,
            cost: 31,
        },
        'X8': {
            name: 'X8',
            price: 33,
            cost: 32,
        },
        'X10': {
            name: 'X10',
            price: 38,
            cost: 37,
        },
        '1101': {
            name: '1101',
            price: 15,
            cost: 13,
        },
        '1188': {
            name: '1188',
            price: 45,
            cost: 43,
        },  
        '1103': {
            name: '1103',
            price: 33,
            cost: 32,
        },   
        '2003': {
            name: '2003',
            price: 24,
            cost: 22,
        },   
        '1109': {
            name: '1109',
            price: 32,
            cost: 28,
        },
        '1118': {
            name: '1118',
            price: 34,
            cost: 32,
        },
        '1118b': {
            name: '1118b',
            price: 38,
            cost: 37,
        },
        '1602': {
            name: '1602',
            price: 20,
            cost: 18.5,
        },
        '1502': {
            name: '1502',
            price: 19,
            cost: 17,
        },
        '1108': {
            name: '1108',
            price: 28,
            cost: 25,
        },
        'tw09': {
            name: 'tw09',
            price: 64,
            cost: 59,
        },
        'tw10': {
            name: 'tw10',
            price: 25,
            cost: 24,
        },
        'tw三指': {
            name: 'tw三指',
            price: 20,
            cost: 17,
        },
        '口红': {
            name: '口红',
            price: 15,
            cost: 15,
        },
        'pro': {
            name: 'pro',
            price: 26,
            cost: 21,
        },
        '美928': {
            name: '美928',
            price: 15,
            cost: 13.5,
        },
        '美928毒液': {
            name: '美928毒液',
            price: 21,
            cost: 19,
        },
        '美928蘑菇头': {
            name: '美928蘑菇头',
            price: 22,
            cost: 20,
        },
        'gt911': {
            name: 'gt911',
            price: 24,
            cost: 22,
        },
        '910a': {
            name: '910a',
            price: 17,
            cost: 16,
        },
        '电池': {
            name: '电池',
            price: 2,
            cost: 2,
        },
        '钥匙扣': {
            name: '钥匙扣',
            price: 4,
            cost: 3.5,
        },
        '20ml': {
            name: '20ml',
            price: 4,
            cost: 3.6,
        },
        '40ml': {
            name: '40ml',
            price: 4,
            cost: 3.6,
        },
        '60ml': {
            name: '60ml',
            price: 5,
            cost: 3.8,
        },
        '110ml': {
            name: '110ml',
            price: 5,
            cost: 4,
        },
        '110水柱': {
            name: '110水柱',
            price: 8,
            cost: 6.5,
        }
    },

    // 获取产品信息
    getProductInfo(model) {
        console.log('开始获取产品信息，型号:', model);
        if (!model) {
            console.log('型号为空，返回null');
            return null;
        }

        // 转换为小写并清理型号
        const cleanModel = model.toLowerCase().replace(/[^a-z0-9]/g, '');
        console.log('清理后的型号:', cleanModel);

        // 存储找到的产品
        const foundProducts = [];

        // 遍历所有产品
        for (const [key, product] of Object.entries(this.items)) {
            // 清理产品键中的非字母数字字符
            const cleanKey = key.toLowerCase().replace(/[^a-z0-9]/g, '');
            console.log('比较:', cleanKey, cleanModel);

            // 检查是否匹配
            if (cleanModel.includes(cleanKey)) {
                console.log('找到匹配产品:', key);
                foundProducts.push(product);
            }
        }

        console.log('找到的产品:', foundProducts);
        return foundProducts.length > 0 ? foundProducts : null;
    },

    // 获取快递费用
    getExpressFees(express) {
        return this.expressFees[express] || this.expressFees['韵达'];
    },

    // 中文数字转阿拉伯数字
    chineseToNumber(chinese) {
        const chineseNumbers = {
            '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
            '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
        };
        const result = chineseNumbers[chinese] || parseInt(chinese);
        console.log('数字转换:', chinese, '->', result);
        return result;
    },

    // 阿拉伯数字转中文数字
    numberToChinese(num) {
        const chineseNumbers = {
            1: '一', 2: '二', 3: '三', 4: '四', 5: '五',
            6: '六', 7: '七', 8: '八', 9: '九', 10: '十'
        };
        return chineseNumbers[num] || num.toString();
    },

    // 识别产品型号
    identifyModel(text) {
        console.log('开始识别产品，输入文本:', text);
        
        // 获取最后一个逗号后的内容
        const parts = text.split(/[，,]/);
        let lastPart = parts[parts.length - 1]?.trim() || '';
        console.log('最后一部分:', lastPart);
        
        // 移除换行符和空格
        lastPart = lastPart.replace(/[\r\n\s]+/g, '').trim();
        console.log('移除换行符后:', lastPart);
        
        if (!lastPart) {
            console.log('没有有效的内容');
            return null;
        }
        
        // 查找数量词（数字+瓶），并处理"发"字
        const quantityMatch = lastPart.match(/(?:发)?([一二三四五六七八九十]|\d+)(瓶)/);
        console.log('数量匹配结果:', quantityMatch);
        
        let model, quantity = '';
        let quantityNum = 1; // 默认数量为1
        
        if (quantityMatch) {
            // 如果找到数量词，用它来分割产品和数量
            const quantityText = quantityMatch[0];
            const quantityIndex = lastPart.indexOf(quantityText);
            // 只保留数量词之前的内容作为产品型号
            model = lastPart.substring(0, quantityIndex).trim().toLowerCase();
            quantityNum = this.chineseToNumber(quantityMatch[1]);
            // 将数字转换为中文显示
            const chineseNum = this.numberToChinese(quantityNum);
            // 设置数量显示
            quantity = ` ${chineseNum}瓶`;
            console.log('找到数量词，分割结果:', {
                model: model,
                quantity: quantity,
                quantityText: quantityText,
                quantityIndex: quantityIndex,
                quantityNum: quantityNum
            });
        } else {
            // 如果没有数量词，整个内容就是产品型号
            model = lastPart.toLowerCase();
            // 设置默认数量显示为空
            quantity = '';
            console.log('未找到数量词，使用整个内容作为产品型号:', model);
        }
        
        // 移除产品型号中的"发"字和名片相关字样
        model = model.replace(/发/g, '')
                    .replace(/名片/g, '')
                    .replace(/不要名片/g, '')
                    .replace(/要名片/g, '')
                    .replace(/加名片/g, '')
                    .replace(/带名片/g, '')
                    .replace(/送名片/g, '')
                    .replace(/放名片/g, '')
                    .replace(/放张名片/g, '')
                    .replace(/放一张名片/g, '')
                    .replace(/放2张名片/g, '')
                    .replace(/放两张名片/g, '')
                    .replace(/放3张名片/g, '')
                    .replace(/放三张名片/g, '')
                    .replace(/放4张名片/g, '')
                    .replace(/放四张名片/g, '')
                    .replace(/放5张名片/g, '')
                    .replace(/放五张名片/g, '')
                    .replace(/放6张名片/g, '')
                    .replace(/放六张名片/g, '')
                    .replace(/放7张名片/g, '')
                    .replace(/放七张名片/g, '')
                    .replace(/放8张名片/g, '')
                    .replace(/放八张名片/g, '')
                    .replace(/放9张名片/g, '')
                    .replace(/放九张名片/g, '')
                    .replace(/放10张名片/g, '')
                    .replace(/放十张名片/g, '');
        
        // 处理钥匙扣后面的ml
        if (model.includes('钥匙扣')) {
            model = model.replace(/钥匙扣\s*ml/i, '钥匙扣');
        }
        
        // 确保没有空格
        model = model.replace(/\s+/g, '');
        
        if (!model) {
            console.log('产品型号为空');
            return null;
        }
        
        // 识别产品组合
        const products = [];
        const allProducts = Object.keys(this.items);
        
        // 按长度排序产品名称，确保先匹配较长的名称
        allProducts.sort((a, b) => b.length - a.length);
        
        let remainingModel = model;
        console.log('开始匹配产品，剩余文本:', remainingModel);
        
        // 支持多产品精确匹配
        while (remainingModel && remainingModel.trim()) {
            let found = false;
            for (const productName of allProducts) {
                // 使用精确匹配
                if (remainingModel.toLowerCase() === productName.toLowerCase()) {
                    const product = this.items[productName];
                    if (product) {
                        products.push(product);
                        console.log('找到精确匹配产品:', productName, product);
                    }
                    remainingModel = '';
                    found = true;
                    break;
                }
            }
            
            if (!found) {
                // 如果没找到完全匹配，尝试查找部分匹配
                for (const productName of allProducts) {
                    if (remainingModel.toLowerCase().includes(productName.toLowerCase())) {
                        const product = this.items[productName];
                        if (product) {
                            products.push(product);
                            console.log('找到部分匹配产品:', productName, product);
                            // 移除已匹配的产品名称
                            remainingModel = remainingModel.toLowerCase().replace(productName.toLowerCase(), '');
                            found = true;
                            break;
                        }
                    }
                }
            }
            
            if (!found) {
                break;
            }
        }
        
        if (products.length === 0) {
            console.log('未找到匹配的产品:', model);
            return null;
        }
        
        console.log('识别到的产品:', products);
        
        // 计算总价格和总成本
        let totalPrice = 0;
        let totalCost = 0;
        
        for (const product of products) {
            // 确保价格和成本是数字
            const price = Number(product.price) || 0;
            const cost = Number(product.cost) || 0;
            
            totalPrice += price;
            totalCost += cost;
            
            console.log('产品价格计算:', {
                name: product.name,
                price: price,
                cost: cost,
                quantity: quantityNum
            });
        }
        
        // 根据数量调整总价格和总成本
        totalPrice *= quantityNum;
        totalCost *= quantityNum;
        
        console.log('最终价格计算:', {
            products: products,
            quantity: quantityNum,
            totalPrice: totalPrice,
            totalCost: totalCost
        });
        
        // 返回带数量的产品型号（用于显示）和价格信息
        return {
            model: model,  // 纯产品型号
            display: quantity ? model + quantity : model,  // 只有在有数量时才显示数量
            price: totalPrice,  // 总价格
            cost: totalCost  // 总成本
        };
    },

    // 识别快递公司
    identifyExpress(text) {
        // 1. 优先检查是否明确指定了快递公司
        if (this.patterns.express.sf.test(text)) {
            return '顺丰';
        }
        if (text.includes('韵达')) {
            return '韵达';
        }
        
        // 2. 检查产品名称是否包含x或X
        const hasX = /[xX]/.test(text);
        if (hasX) {
            return '顺丰';
        }
        
        // 3. 默认返回韵达
        return this.patterns.express.default;
    },

    // 识别省份
    identifyProvince(text) {
        let firstProvince = '';
        let firstPosition = Infinity;
        
        // 遍历所有省份，找到在文本中出现位置最靠前的省份
        for (const [province, pattern] of Object.entries(this.patterns.provinces)) {
            const match = text.match(pattern);
            if (match) {
                const position = text.indexOf(match[0]);
                if (position < firstPosition) {
                    firstPosition = position;
                    firstProvince = province;
                }
            }
        }
        
        return firstProvince;
    }
}

const app = createApp({
    setup() {
        const inputForm = ref({
            text: ''
        })
        const tableData = ref([])
        const fileInput = ref(null)

        // 生成6位随机数ID
        const generateId = () => {
            return Math.floor(100000 + Math.random() * 900000).toString()
        }

        // 保存数据到localStorage
        const saveToLocalStorage = () => {
            try {
                localStorage.setItem('orderData', JSON.stringify(tableData.value))
                console.log('数据已保存到localStorage')
            } catch (error) {
                console.error('保存到localStorage失败:', error)
            }
        }

        // 从localStorage加载数据
        const loadFromLocalStorage = () => {
            try {
                const savedData = localStorage.getItem('orderData')
                if (savedData) {
                    const parsedData = JSON.parse(savedData)
                    tableData.value = parsedData
                    console.log('从localStorage加载数据:', parsedData)
                }
            } catch (error) {
                console.error('从localStorage加载数据失败:', error)
            }
        }

        // 从localStorage删除指定ID的数据
        const removeFromLocalStorage = (id) => {
            try {
                const currentData = tableData.value.filter(item => item.id !== id)
                localStorage.setItem('orderData', JSON.stringify(currentData))
                console.log('已从localStorage删除ID为', id, '的数据')
            } catch (error) {
                console.error('从localStorage删除数据失败:', error)
            }
        }

        // 清空所有数据
        const clearAllData = () => {
            ElMessageBox.confirm(
                '此操作将清空所有表格数据和本地缓存，且无法恢复。是否继续？',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                try {
                    // 清空表格数据
                    tableData.value = []
                    // 清空localStorage
                    localStorage.removeItem('orderData')
                    console.log('已清空所有数据和本地缓存')
                    ElMessage.success('数据已清空')
                } catch (error) {
                    console.error('清空数据失败:', error)
                    ElMessage.error('清空数据失败')
                }
                         }).catch(() => {
                 ElMessage.info('已取消清空操作')
             })
        }

        // 触发文件选择
        const importTable = () => {
            fileInput.value.click()
        }

        // 处理文件导入
        const handleFileImport = async (event) => {
            const file = event.target.files[0]
            if (!file) {
                return
            }

            try {
                const buffer = await file.arrayBuffer()
                const workbook = new ExcelJS.Workbook()
                await workbook.xlsx.load(buffer)
                
                // 获取第一个工作表
                const worksheet = workbook.getWorksheet(1)
                if (!worksheet) {
                    ElMessage.error('Excel文件中没有找到工作表')
                    return
                }

                const importedData = []
                let isFirstRow = true

                // 遍历所有行
                worksheet.eachRow((row, rowNumber) => {
                    // 跳过标题行
                    if (isFirstRow) {
                        isFirstRow = false
                        return
                    }

                    // 跳过总计和利润行
                    const firstCellValue = row.getCell(1).value
                    if (firstCellValue === '总计' || firstCellValue === '利润') {
                        return
                    }

                    // 获取行数据
                    const values = row.values
                    if (!values || values.length < 10) {
                        return // 跳过空行或数据不完整的行
                    }

                    // 创建数据对象
                    const rowData = {
                        id: generateId(), // 生成新的ID
                        name: values[1] || '',
                        product: values[2] || '',
                        express: values[3] || '韵达',
                        shippingFee: Number(values[4]) || 0,
                        amount: Number(values[5]) || 0,
                        totalAmount: Number(values[6]) || 0,
                        shippingCost: Number(values[7]) || 0,
                        cost: Number(values[8]) || 0,
                        totalCost: Number(values[9]) || 0,
                        remark: values[10] || ''
                    }

                    // 验证必要字段
                    if (rowData.name) {
                        importedData.push(rowData)
                    }
                })

                if (importedData.length === 0) {
                    ElMessage.warning('Excel文件中没有找到有效数据')
                    return
                }

                // 询问用户是替换还是追加数据
                ElMessageBox.confirm(
                    `检测到 ${importedData.length} 条数据。选择导入方式：`,
                    '导入数据',
                    {
                        confirmButtonText: '替换现有数据',
                        cancelButtonText: '追加到现有数据',
                        distinguishCancelAndClose: true,
                        type: 'info',
                    }
                ).then(() => {
                    // 替换现有数据
                    tableData.value = importedData
                    saveToLocalStorage()
                    ElMessage.success(`已替换导入 ${importedData.length} 条数据`)
                }).catch((action) => {
                    if (action === 'cancel') {
                        // 追加到现有数据
                        tableData.value.push(...importedData)
                        saveToLocalStorage()
                        ElMessage.success(`已追加导入 ${importedData.length} 条数据`)
                    }
                })

            } catch (error) {
                console.error('导入文件失败:', error)
                ElMessage.error('导入文件失败，请检查文件格式是否正确')
            } finally {
                // 清空文件输入框
                event.target.value = ''
            }
        }

        const grandTotalAmount = computed(() => {
            return Number(tableData.value.reduce((sum, row) => sum + Number(row.totalAmount), 0).toFixed(2))
        })

        const grandTotalCost = computed(() => {
            return Number(tableData.value.reduce((sum, row) => sum + Number(row.totalCost), 0).toFixed(2))
        })

        const totalProfit = computed(() => {
            const profit = Number(grandTotalAmount.value) - Number(grandTotalCost.value)
            return Number(profit.toFixed(2))
        })

        const parseInputText = (text) => {
            // 找到第一个逗号的位置（支持中英文逗号）
            const firstCommaIndex = text.search(/[，,]/)
            if (firstCommaIndex === -1) {
                throw new Error('输入格式不正确，请确保包含逗号分隔符')
            }

            // 提取姓名（第一个逗号之前的内容）
            let name = text.substring(0, firstCommaIndex)
            
            // 处理姓名中的中括号
            name = name.replace(/\[.*?\]/g, '')
            console.log(name);
            if (!name) {
                throw new Error('未能识别姓名')
            }

            // 识别省份
            const province = products.identifyProvince(text)

            // 使用产品配置识别产品型号（最后一个逗号后的内容）
            const productResult = products.identifyModel(text)
            if (!productResult) {
                throw new Error('未能识别产品型号')
            }

            // 使用产品配置识别快递公司
            const express = products.identifyExpress(text)
            // 获取快递费用
            const expressFees = products.getExpressFees(express)

            // 返回解析结果
            return {
                name,           // 设置姓名
                product: productResult.display,  // 使用带数量的显示格式
                express,        // 设置快递公司
                shippingFee: expressFees.shippingFee,    // 设置运费
                shippingCost: expressFees.shippingCost,   // 设置运费成本
                amount: productResult.price,  // 使用计算好的总价格
                cost: productResult.cost,      // 使用计算好的总成本
                remark: province  // 添加省份备注
            }
        }

        const calculateRowTotals = (row) => {
            row.totalAmount = Number((Number(row.amount) + Number(row.shippingFee)).toFixed(2))
            row.totalCost = Number((Number(row.cost) + Number(row.shippingCost)).toFixed(2))
        }

        const addRowFromInput = () => {
            console.log('开始添加行，输入内容:', inputForm.value.text);
            
            if (!inputForm.value.text) {
                ElMessage.warning('请输入内容');
                return;
            }

            try {
                // 解析输入文本
                const parts = inputForm.value.text.split(/[，,]/);
                if (parts.length < 2) {
                    ElMessage.warning('请输入正确的格式：姓名，产品');
                    return;
                }

                const name = parts[0].trim();
                const productText = parts.slice(1).join(',').trim();
                
                console.log('解析结果:', {
                    name: name,
                    productText: productText
                });

                // 识别产品信息
                console.log(inputForm.value.text,22);
                
                const productInfo = products.identifyModel(inputForm.value.text);
                console.log('产品识别结果:', productInfo);

                if (!productInfo) {
                    ElMessage.warning('未找到匹配的产品');
                    return;
                }

                // 识别省份
                const province = products.identifyProvince(inputForm.value.text);

                // 设置默认快递和运费
                let express = products.identifyExpress(inputForm.value.text);  // 使用identifyExpress方法识别快递
                let shippingFee = 0;
                let shippingCost = 0;

                // 获取快递费用
                const expressFees = products.getExpressFees(express);
                if (expressFees) {
                    shippingFee = expressFees.shippingFee || 0;
                    shippingCost = expressFees.shippingCost || 0;
                }

                console.log('快递信息:', {
                    express: express,
                    expressFees: expressFees,
                    shippingFee: shippingFee,
                    shippingCost: shippingCost
                });

                // 创建新行
                const newRow = {
                    id: generateId(), // 生成6位随机数ID
                    name: name,
                    product: productInfo.display,
                    express: express,
                    shippingFee: Number(Number(shippingFee).toFixed(2)),
                    amount: Number(Number(productInfo.price || 0).toFixed(2)),
                    totalAmount: Number((Number(productInfo.price || 0) + Number(shippingFee)).toFixed(2)),
                    shippingCost: Number(Number(shippingCost).toFixed(2)),
                    cost: Number(Number(productInfo.cost || 0).toFixed(2)),
                    totalCost: Number((Number(productInfo.cost || 0) + Number(shippingCost)).toFixed(2)),
                    remark: province  // 添加省份备注
                };

                console.log('准备添加的新行:', newRow);

                // 添加到表格
                tableData.value.push(newRow);
                console.log('成功添加到表格');

                // 保存到localStorage
                saveToLocalStorage();

                // 重置输入表单
                inputForm.value = {
                    text: '',
                    express: '韵达',  // 重置为默认快递
                    expressFee: 0,
                    expressCost: 0
                };

                ElMessage.success('添加成功');
            } catch (error) {
                console.error('添加行时出错:', error);
                ElMessage.error('添加失败，请检查输入格式');
            }
        }

        const deleteRow = (index) => {
            // 获取要删除的行的ID
            const rowToDelete = tableData.value[index]
            if (rowToDelete && rowToDelete.id) {
                console.log('删除ID为', rowToDelete.id, '的数据')
            }
            
            // 从表格中删除
            tableData.value.splice(index, 1)
            
            // 更新localStorage
            saveToLocalStorage()
        }

        // 导出表格
        const exportTable = async () => {
            try {
                // 创建工作簿
                const workbook = new ExcelJS.Workbook()
                const worksheet = workbook.addWorksheet('订单数据')

                // 设置工作表默认行高
                worksheet.properties.defaultRowHeight = 25

                // 工具函数：清理单元格内容，去除换行并限制长度
                function sanitizeCellContent(val) {
                    if (typeof val === 'string') {
                        return val.replace(/[\r\n]+/g, '').slice(0, 30);
                    }
                    return val;
                }

                // 设置列宽
                worksheet.columns = [
                    { header: '姓名', key: 'name', width: 20 },
                    { header: '产品', key: 'product', width: 25 },
                    { header: '快递', key: 'express', width: 10 },
                    { header: '运费', key: 'shippingFee', width: 10 },
                    { header: '金额', key: 'amount', width: 10 },
                    { header: '总金额', key: 'totalAmount', width: 10 },
                    // { header: '运费成本', key: 'shippingCost', width: 10 },
                    // { header: '成本', key: 'cost', width: 10 },
                    // { header: '总成本', key: 'totalCost', width: 10 },
                    { header: '备注', key: 'remark', width: 10 }
                ]

                // 设置表头样式
                const headerRow = worksheet.getRow(1)
                headerRow.height = 25  // 明确设置表头行高
                headerRow.eachCell((cell) => {
                    cell.alignment = {
                        vertical: 'middle',
                        horizontal: 'center'
                    }
                    cell.font = {
                        bold: true,
                        size: 11,
                        name: 'Arial'
                    }
                    cell.fill = {
                        type: 'pattern',
                        pattern: 'solid',
                        fgColor: { argb: 'FFE0E0E0' }
                    }
                    cell.border = {
                        top: { style: 'thin' },
                        left: { style: 'thin' },
                        bottom: { style: 'thin' },
                        right: { style: 'thin' }
                    }
                })

                // 添加数据行
                tableData.value.forEach((row, index) => {
                    const dataRow = worksheet.addRow([
                        sanitizeCellContent(row.name),
                        sanitizeCellContent(row.product),
                        sanitizeCellContent(row.express),
                        row.shippingFee,
                        row.amount,
                        row.totalAmount,
                        // row.shippingCost,
                        // row.cost,
                        // row.totalCost,
                        sanitizeCellContent(row.remark)
                    ]);
                    // 明确设置数据行高度为25
                    dataRow.height = 25;
                    dataRow.eachCell((cell) => {
                        cell.alignment = {
                            vertical: 'middle',
                            horizontal: 'center',
                            wrapText: false
                        };
                        cell.font = {
                            size: 11,
                            name: 'Arial'
                        };
                        cell.border = {
                            top: { style: 'thin' },
                            left: { style: 'thin' },
                            bottom: { style: 'thin' },
                            right: { style: 'thin' }
                        };
                    });
                });

                // 添加总计行
                const totalRow = worksheet.addRow([
                    '合计', '', '', '', '', grandTotalAmount.value, ''
                ]);
                totalRow.height = 25;  // 明确设置总计行高度
                totalRow.eachCell((cell) => {
                    cell.alignment = {
                        vertical: 'middle',
                        horizontal: 'center',
                        wrapText: false
                    };
                    cell.font = {
                        bold: true,
                        size: 11,
                        name: 'Arial'
                    };
                    cell.border = {
                        top: { style: 'thin' },
                        left: { style: 'thin' },
                        bottom: { style: 'thin' },
                        right: { style: 'thin' }
                    };
                });

                // 添加利润行
                // const profitRow = worksheet.addRow([
                //     '利润', '', '', '', '', totalProfit.value, '', '', '', ''
                // ]);
                // profitRow.height = 25;  // 明确设置利润行高度
                // profitRow.eachCell((cell) => {
                //     cell.alignment = {
                //         vertical: 'middle',
                //         horizontal: 'center',
                //         wrapText: false
                //     };
                //     cell.font = {
                //         bold: true,
                //         size: 11,
                //         name: 'Arial'
                //     };
                //     cell.border = {
                //         top: { style: 'thin' },
                //         left: { style: 'thin' },
                //         bottom: { style: 'thin' },
                //         right: { style: 'thin' }
                //     };
                // });

                // 强制设置所有行的行高为25（确保没有遗漏）
                for (let rowNumber = 1; rowNumber <= worksheet.rowCount; rowNumber++) {
                    const row = worksheet.getRow(rowNumber);
                    row.height = 25;
                }

                // 生成文件名
                const fileName = `订单数据_${new Date().toLocaleDateString()}.xlsx`

                // 导出文件
                const buffer = await workbook.xlsx.writeBuffer()
                const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                saveAs(blob, fileName)

                ElMessage.success('导出成功')
            } catch (error) {
                console.error('导出失败:', error)
                ElMessage.error('导出失败: ' + error.message)
            }
        }

        // 监听表格数据变化
        watch(tableData, (newVal) => {
            newVal.forEach(row => {
                calculateRowTotals(row)
            })
        }, { deep: true })

        // 页面初始化时加载localStorage数据
        loadFromLocalStorage()

        return {
            inputForm,
            tableData,
            fileInput,
            grandTotalAmount,
            grandTotalCost,
            totalProfit,
            addRowFromInput,
            deleteRow,
            exportTable,
            importTable,
            handleFileImport,
            loadFromLocalStorage,
            saveToLocalStorage,
            clearAllData
        }
    }
})

// 使用Element Plus
app.use(ElementPlus)

// 添加自定义样式
const style = document.createElement('style')
style.textContent = `
    .table-container {
        max-height: calc(100vh - 200px); /* 减去其他元素的高度，预留足够空间 */
        overflow-y: auto;
        margin-bottom: 20px;
        padding-right: 10px; /* 为滚动条预留空间 */
    }
    
    .input-container {
        position: sticky;
        top: 0;
        background: white;
        padding: 20px 0;
        z-index: 1;
    }
    
    .summary-container {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-bottom: 20px;
        position: sticky;
        bottom: 0;
        background: white;
        padding: 10px 0;
        z-index: 1;
    }
    
    .summary-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .summary-label {
        font-weight: bold;
    }
    
    .export-button {
        margin-left: auto;
    }

    /* 添加表格滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 6px;
    }
    
    .table-container::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }
    
    .table-container::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;
    }
    
    .table-container::-webkit-scrollbar-thumb:hover {
        background: #555;
    }

    /* 确保表格内容区域有足够的内边距 */
    .el-table {
        margin-bottom: 20px;
    }

    /* 确保表格头部固定 */
    .el-table__header-wrapper {
        position: sticky;
        top: 0;
        z-index: 2;
        background: white;
    }
`
document.head.appendChild(style)

app.mount('#app')